package com.btjava.maven.pomver.handler;

import com.btjava.maven.pomver.utils.XmlParseUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class WorkSpaceXmlHandler {
    /**
     * 获取当前项目的maven配置
     * @param filePath workSpace.xml路径
     * @return maven配置路径
     */
    public static String getMavenSetting(String filePath){
        List<Element> elementList = XmlParseUtils.getElementByNamePath(filePath,"[name=MavenImportPreferences]>[name=generalSettings]>MavenGeneralSettings>option");
        if(Objects.isNull(elementList) || elementList.isEmpty()){
            return null;
        }
        return elementList.get(0).attributeValue("value");
    }

    /**
     * 将选择的maven仓库地址保存下来备用
     * @param filePath workSpace.xml路径
     * @param repositoryUrl 选中的maven仓库地址
     */
    public static void addMavenRepository(String filePath,String repositoryUrl){
        Document doc =XmlParseUtils.getDocument(filePath);
        if(Objects.isNull(doc)){
            return;
        }
        if(StringUtils.isBlank(repositoryUrl)){
            return;
        }
        List<Element> elementList = XmlParseUtils.getElementByNamePath(filePath,"[name=projectMaven]>[name=repositoryUrl]");
        if(Objects.isNull(elementList) || elementList.isEmpty()){
            addElement(doc,repositoryUrl);
            XmlParseUtils.saveXml(doc,filePath);
            return;
        }
        List<String> urlList = new ArrayList<>();
        for(Element e :elementList){
            urlList.add(e.getTextTrim()) ;
        }
        //先查询，再更新
        if(urlList.contains(repositoryUrl)){
            return;
        }
        Element element = elementList.get(0);
        element.setText(repositoryUrl);
        //更新
        XmlParseUtils.saveXml(element.getDocument(),filePath);
    }

    private static void addElement(Document doc,String repositoryUrl){
        //新增节点
        Element root =doc.getRootElement();
        Element element = root.addElement("component");
        element.addAttribute("name","projectMaven");
        Element url =element.addElement("url");
        url.addAttribute("name","repositoryUrl");
        url.setText(repositoryUrl);
    }

    /**
     * 获取默认的maven仓库地址
     * @param filePath workSpace.xml文件地址
     * @return
     */
    public static String getMavenRepositoryUrl(String filePath){
        List<Element> elementList = XmlParseUtils.getElementByNamePath(filePath,"[name=projectMaven]>[name=repositoryUrl]");
        if(Objects.isNull(elementList) || elementList.isEmpty()){
            return null;
        }
        return elementList.get(0).getTextTrim();
    }
}
